package net.cctms.zhishu.webAppFramework.utils;

import android.text.TextUtils;

import java.util.regex.Matcher;
import java.util.regex.Pattern;


/**
 * 链接处理工具类
 */
public class UrlUtil {
    public static String patternUrl = "((http[s]{0,1}|ftp)://[a-zA-Z0-9\\.\\-]+\\.([a-zA-Z]{2,4})(:\\d+)?(/[a-zA-Z0-9\\.\\-~!@#$%^&;*+?:_/=<>]*)?)|(www.[a-zA-Z0-9\\.\\-]+\\.([a-zA-Z]{2,4})(:\\d+)?(/[a-zA-Z0-9\\.\\-~!@#$%^&;*+?:_/=<>]*)?)";

    /**
     * 判断字符串是否为Url
     *
     * @param str
     * @return url
     */
    public static boolean isUrl(String str) {
        if (TextUtils.isEmpty(str)) {
            return false;
        }
        Pattern pattern = Pattern.compile(patternUrl);
        Matcher matcher = pattern.matcher(str);
        return matcher.matches();
    }

    /**
     * 判断字符串是否为Url
     *
     * @param str
     * @return url
     */
    public static String getUrlFromString(String str) {
        String result = "";
        if (!TextUtils.isEmpty(str)) {
            Pattern pattern = Pattern.compile(patternUrl);
            Matcher matcher = pattern.matcher(str);
            if (matcher.find()) {
                result = matcher.group();
            }
        }
        return result;
    }


    /**
     * 根据图片地址，获取图片的文件名
     *
     * @param imageUrl
     * @return
     */
    public static String getImageFileName(String imageUrl) {
        if (!TextUtils.isEmpty(imageUrl)) {
            String fileName = imageUrl.substring(imageUrl.lastIndexOf("/") + 1);
            return fileName;
        }
        return null;
    }

    /**
     * 获取图片Url的后缀
     *
     * @return
     */
    public static String getUrlPostfix(String urlStr) {
        String postfix = "";
        if (!TextUtils.isEmpty(urlStr)) {
            int subStringStartPos = urlStr.lastIndexOf(".") + 1;
            if (urlStr.length() >= subStringStartPos) {
                postfix = urlStr.substring(subStringStartPos);
            }
        }
        return postfix;
    }

    /**
     * 生成分享链接
     * !!!!!!!!需要修改
     *
     * @param url 文章contentUrl
     * @return 分享链接
     */
    public static String getArticleShareUrl(String url) {
        return TextUtils.isEmpty(url) ? "" : url + "?o=" + UserInfoUtil.getOpenId();
    }

}
